import peewee as pw

from app.auth.models import User
from db.base_model import BaseModel, db


class Text(BaseModel):
    user_id = pw.CharField(max_length=128, null=False)
    content = pw.TextField()

    class Meta:
        table_name = "text"

    @classmethod
    def get_all_displays(cls, user_id, page_size, page_number, keyword=None):
        # 获取文本内容信息
        limit = page_size
        offset = (page_number - 1) * page_size
        query = cls.select().where(cls.user_id == user_id)
        if keyword:
            query = query.where(cls.content.contains(keyword))
        total = query.count()
        res = query.order_by(cls.id.desc()).offset(offset).limit(limit)
        displays_data = [c.to_dict() for c in res]
        return total, displays_data

    @classmethod
    def update_by_id(cls, user_id, _id, args):
        # 检查是否存在该demo_id，如果不存在则抛出异常404
        text = cls.get(cls.id == _id, cls.user_id == user_id)
        cls.update(**args).where(cls.id == _id).execute()
        user = User.get(user_id=user_id)
        user.word_count = user.word_count - len(text.content) + len(args["content"])
        user.save()

    @classmethod
    def delete_row(cls, user_id, _id):
        with db.atomic():
            res = cls.get(cls.user_id == user_id, cls.id == _id)
            user = User.get(user_id=user_id)
            content_count = user.content_count - 1
            word_count = user.word_count - len(res.content)
            User.update(
                **{"content_count": content_count, "word_count": word_count}
            ).where(User.user_id == user_id).execute()
            res.delete_instance()

    @classmethod
    def delete_oldest_content(cls, user_id):
        with db.atomic():
            oldest_content = (
                cls.select().where(cls.user_id == user_id).order_by(cls.id).first()
            )
            oldest_content.delete_instance()
            user = User.get(User.user_id == user_id)
            user.content_count -= 1
            user.word_count -= len(oldest_content.content)
            user.save()
